<template>
  <div>
    <el-table
      v-if="data.length"
      header-row-class-name="base-table-header-v3"
      row-class-name="base-table-row-v3"
      :data="data"
      border>
      <el-table-column
        v-for="(column, index) in colums"
        :key="`${column.field}_${index}`"
        :label="column.label"
        :prop="column.field"
        show-overflow-tooltip
        :width="column.width">
        <template slot-scope="scope">
          <!-- start 小计 -->
          <template v-if="column.field === 'total'">
            <span>
              {{ getToTalPrice(scope.row) }} <span v-if="internationalGray">{{settlementCurrency}}</span>
            </span>
          </template>
          <!-- end 小计 -->

          <!-- start 质保状态 -->
          <template v-else-if="column.field === 'serviceQualityStatus'">
            {{ getServiceQualityStatus(scope.row.serviceQualityStatus) }}
          </template>
          <!-- end 质保状态 -->

          <!-- start 单价 -->
          <template v-else-if="column.field === 'salePrice'">
            {{ scope.row | fmt_salePrice_currency }}
          </template>
          <!-- end 单价 -->

          <!-- start 折扣费用 -->
          <template v-else-if="column.field === 'reductionFee' && isServiceItemDiscountSettings">
            {{ getReductionFeeVal(scope.row) }}
          </template>
          <!-- end 折扣费用 -->

          <!-- start 汇率换算方式 -->
          <template v-else-if="column.field === 'exchangeMethod'">
            {{ getExchangeMethods(scope.row.exchangeMethod) }}
          </template>
          <!-- end 汇率换算方式 -->

          <!-- start 汇率 -->
          <template v-else-if="column.field === 'exchangeRate'">
            {{ scope.row.exchangeRate }}
          </template>
          <!-- end 汇率 -->

          <!-- start 换算后单价 -->
          <template v-else-if="column.field === 'conversionPrice'">
            <span>
            {{ (scope.row.salePrice * scope.row.exchangeRate).toFixed(2) }} <span v-if="internationalGray">{{settlementCurrency}}</span>
            </span>
          </template>
          <!-- end 换算后单价 -->

          <!-- start 备件返还仓库名称 -->
          <template v-else-if="column.field === 'repertoryId' && isSparePartsReturnExpense">
            <template v-if="scope.row.isPerson">
              <template v-if="isOpenData && scope.row.staffId">
                <open-data type="userName" :openid="scope.row.staffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row['repertoryName'] || '' }}
              </template>
            </template>
            <template v-else>
              {{ scope.row['repertoryName'] || '' }}
            </template>
          </template>
          <!-- end 备件返还仓库名称 -->

          <!-- start 安装产品id获取安装产品名称 -->
          <template v-else-if="column.field === 'installProductId'">
            {{ getProductName(scope.row[column.field]) }}
          </template>
          <template v-else-if="column.formType === 'address'">
            {{ scope.row[column.field] | fmt_address}}
          </template>
          <template v-else-if="column.formType === 'select'">
            {{Array.isArray(scope.row[column.field]) ? scope.row[column.field].join(',') : scope.row[column.field]}}
          </template>
          <!-- end  安装产品id获取安装产品名称 -->
          <template v-else-if="column.field === 'repertoryName'">
            <template v-if="isOpenData && scope.row.repertoryStaffId">
              <open-data type="userName" :openid="scope.row.repertoryStaffId"></open-data>
            </template>
            <template v-else>
              {{ scope.row[column.field] }}
            </template>
          </template>
          <template v-else-if="column.field === 'snList'">
            {{Array.isArray(scope.row[column.field]) ? scope.row[column.field].join(',') : scope.row[column.field]}}
          </template>
          <template v-else-if="column.field === 'replacedSnList'">
            {{Array.isArray(scope.row[column.field]) ? scope.row[column.field].join(',') : scope.row[column.field]}}
          </template>
          <template v-else-if="column.field === 'replacedMaterial'">
            {{ scope.row.replacedMaterial ? (scope.row.replacedMaterial.name || scope.row.replacedMaterial.materialName) : ''}}
          </template>
          <template v-else-if="column.field === 'recordNo'">
            <template v-if="scope.row.attribute">
              <div v-if="scope.row.attribute.recordNo" class="form-view-row-content-link-text" @click='openOutTab(scope.row.attribute)'>
                {{scope.row.attribute.recordNo}}
              </div>
            </template>
          </template>
          <template v-else-if="column.field === 'SN'">
            {{ scope.row.sn }}
          </template>
          <template v-else-if="column.field === 'batchNumber'">
            <span>{{ scope.row.batchNumber ? scope.row.batchNumber : scope.row.batchNumberList && scope.row.batchNumberList.join() }}</span>
          </template>
          <template v-else-if="column.setting && column.setting.originalFormType === 'richtext'">
            <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
              <span v-if="scope.row && (scope.row.attribute && scope.row.attribute[column.fieldName]) || (scope.row[column.fieldName])">{{$t('common.base.view')}}</span>
            </div>
          </template>
          <template v-else>{{ $formatFormField(column, scope.row) }}</template>
        </template>
      </el-table-column>
    </el-table>
    <!-- start sn弹窗 -->
    <receipt-sn-dialog ref="receiptSnDialog" />
    <!-- end sn弹窗 -->

    <!-- 富文本弹窗 -->
    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import ReceiptSnDialog from './ReceiptSnDialog';
import { exchangeMethodsOption } from '@src/util/currency'
import { getProductQualityStatusText } from '@src/util/qualityInfoConfig'
/* utils */
import { getRootWindow } from '@src/util/dom'
import NP from 'number-precision';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
export default {
  name: 'receipt-view-common-table',
  inject: ['initData'],
  props: {
    data: {
      type: Array,
      default: () => ([])
    },
    colums: {
      type: Array,
      default: () => ([])
    },
    settlementCurrency: {
      type: String,
      default: 'CNY'
    },
    type: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      isOpenData,
      exchangeMethodsOption,
      internationalGray
    }
  },
  computed: {
    // 服务项目折扣灰度
    isServiceItemDiscountSettings() {
      const RootWindow = getRootWindow(window)
      return Boolean(RootWindow.grayAuth?.serviceItemDiscountSettings)
    },
    isSparePartsReturnExpense() {
      return this.type === 'sparePartsReturnExpense';
    }
  },
  methods: {
    // 折扣费用
    getReductionFeeVal(item){
      const reductionFee = item.reductionFee ? item.reductionFee: 0
      // 国际化灰度
      if(internationalGray) {
        return `${reductionFee} ${this.settlementCurrency}`
      }
      return reductionFee
    },
    getToTalPrice(item) {
      let { number, salePrice, exchangeRate, reductionFee } = item
      // 服务项目折扣灰度
      if (this.isServiceItemDiscountSettings && reductionFee) {
        // 小计 = 用量 * 单价 - 折扣费用
        return NP.minus(NP.times(number, salePrice), reductionFee)
      }
      
      if(this.internationalGray) {
        return (number * salePrice * exchangeRate).toFixed(2)
      }else {
        return (number * salePrice).toFixed(2)
      }
    },
    // 质保状态国际化
    getServiceQualityStatus(value){
      return getProductQualityStatusText(value)
    },
    getExchangeMethods(value) {
      let methodItem = exchangeMethodsOption.find(item => item.value == value) || {}
      return methodItem?.text || ''
    },
    // 根据产品id获取产品名称
    getProductName(id) {
      let name = ''
      this.initData.task.products.forEach(product => {
        if (id == product.id) {
          name = product.name
        }
      })
      return name
    },
    openSnDialog(type, row, index) {
      this.$refs.receiptSnDialog.open(type, row, index)
    },
    openOutTab(attribute) {
      if (!attribute.recordId) return;
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageIntostockDetail,
        key: attribute.recordNo,
        titleKey: attribute.recordNo,
        params: `id=${attribute.recordId}`,
        fromId
      })
    },
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.[column.fieldName] || row?.attribute?.[column.fieldName] || '';
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId, false, true);
    }
  },
  components: {
    [ReceiptSnDialog.name]: ReceiptSnDialog
  }
}
</script>
<style lang="scss" scoped>
  .form-view-row-content-link-text {
    color: $color-primary-light-6 !important;
    cursor: pointer;
  }
</style>
